package com.telecom.weixi.net;

import java.io.InterruptedIOException;
import java.net.SocketException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;

import android.os.Handler;

import com.telecom.weixi.WeixiApplication;
import com.telecom.weixi.net.ReqParam.ReqType;
import com.telecom.weixi.util.Utils;

public class WebServiceEngine {

	private static final String URL = WeixiApplication.WSDL_URL;
	// http://60.164.227.235:9999/gscdm/services/GscdService?wsdl
	public static final String NAME_SPACE = WeixiApplication.WSDL_NAME_SPACE;
	private static final String SOAP_ACTION = "";

	static int TIME_OUT = 5000;

	public static final String TagUserId = "userId";
	public static final String TagLatnId = "latn_id";
	public static final String TagPageSize = "pageSize";
	public static final String TagPageNo = "pageNo";

	public void writeFileData(String fileName, String message, boolean append) {
		// try {
		// FileOutputStream output = new FileOutputStream("/sdcard/"
		// + fileName + ".txt", append);
		// byte[] bytes = message.getBytes();
		// output.write(bytes);
		// output.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// Debug("write err: " + e.getMessage());
		// }
	}

	public static final String TagPMenuId = "parentMenuId";

	public void getMenuList(String userId, String parentMenuId) {
		Debug("getMenuList " + userId + "-" + parentMenuId);
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.GetMenuList);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagPMenuId, parentMenuId);

		ReqParam req = new ReqParam(ReqType.GetMenuList, reqSoap, ReqParam.GetMenuList);
		sendReqAsync(req);

	}

	public static final String TagAccNbr = "acc_nbr";

	public void getAccNbrSearchAsync(String userId, String accNbr, String latnId, int pageSize, int pageNo) {
		Debug("getAccNbrSearchAsync " + userId + "-" + accNbr + "-" + latnId);
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.GetAccNBrSearch);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagAccNbr, accNbr);
		reqSoap.addProperty(TagLatnId, latnId);
		reqSoap.addProperty(TagPageSize, pageSize);
		reqSoap.addProperty(TagPageNo, pageNo);

		ReqParam req = new ReqParam(ReqType.GetAccNBrSearch, reqSoap, ReqParam.GetAccNBrSearch);
		sendReqAsync(req);
	}

	public static final String TagServName = "serv_name";

	public void getUserNameSearch(String userId, String servName, String latnId, int pageSize, int pageNo) {
		Debug("getUserNameSearch " + userId + "-" + servName + "-" + latnId);
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.GetUserNameSearch);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagServName, servName);
		reqSoap.addProperty(TagLatnId, latnId);
		reqSoap.addProperty(TagPageSize, pageSize);
		reqSoap.addProperty(TagPageNo, pageNo);

		ReqParam req = new ReqParam(ReqType.GetUserNameSearch, reqSoap, ReqParam.GetUserNameSearch);
		sendReqAsync(req);
	}

	private static final String TagLMenuId = "lower_menu_id";

	public void getCustInfoItem(String userId, String lowerMenuId) {
		Debug("getCustInfoItem " + userId + "-" + lowerMenuId);

		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.GetCustInfoItem);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagLMenuId, lowerMenuId);

		ReqParam req = new ReqParam(ReqType.GetCustInfoItem, reqSoap, ReqParam.GetCustInfoItem);
		sendReqAsync(req);
	}

	private static final String TagCustId = "cust_id";
	// public void getCustBaseInfo(String userId, String custId){
	// SoapObject reqSoap = new SoapObject(NAME_SPACE,
	// ReqParam.GetCustBaseInfo);
	// reqSoap.addProperty(TagUserId, userId);
	// reqSoap.addProperty(TagCustId, custId);
	//
	// ReqParam req = new ReqParam(ReqType.GetCustBaseInfo, reqSoap,
	// NAME_SPACE);
	// sendReqAsync(req);
	// }

	private static final String TagServId = "serv_id";
	private static final String TagAcctMonth = "acct_month";

	public void getXBaseInfo(ReqParam.ReqType type, String method, String uId, String id) {
		getXBaseInfo(type, method, uId, id, null);
	}

	public void getXBaseInfo(ReqParam.ReqType type, String method, String uId, String id, String month) {
		Debug("getXBaseInfo " + type.toString() + "-" + method + "-" + uId + "-" + id + "-" + month);
		SoapObject reqSoap = new SoapObject(NAME_SPACE, method);
		reqSoap.addProperty(TagUserId, uId);
		boolean available = false;
		switch (type) {
		case GetCustBaseInfo:
			available = true;
			reqSoap.addProperty(TagCustId, id);
			break;
		case GetUserBaseInfo:
		case GetProductInfo:
		case GetOfferOrderInfo:
		case GetAttrProdBaseInfo:
		case GetOfferBaseInfo:
		case GetOfferInstBaseInfo:
			available = true;
			reqSoap.addProperty(TagServId, id);
			break;
		case GetMonthAcctBaseInfo:
			available = true;
			reqSoap.addProperty(TagServId, id);
			reqSoap.addProperty(TagAcctMonth, month);
			break;
		default:
		}

		if (available) {
			ReqParam req = new ReqParam(type, reqSoap, method);
			sendReqAsync(req);
		}
	}

	public void getTerminalInfo(String userId, String accNbr) {
		Debug("getTerminalInfo " + userId + "-" + accNbr);
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.GetTerminalInfo);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagAccNbr, accNbr);

		ReqParam req = new ReqParam(ReqType.GetTerminalInfo, reqSoap, ReqParam.GetTerminalInfo);
		sendReqAsync(req);
	}

	public void getTerminalInfodetail(String userId, String accNbr, int pageSize, int pageNo) {
		Debug("getTernInfoDetail " + userId + "-" + accNbr);
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.GetTerminalInfodetail);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagAccNbr, accNbr);
		reqSoap.addProperty(TagPageSize, pageSize);
		reqSoap.addProperty(TagPageNo, pageNo);

		ReqParam req = new ReqParam(ReqType.GetTerminalInfodetail, reqSoap, ReqParam.GetTerminalInfodetail);
		sendReqAsync(req);
	}

	public void getOweInfo(String userId, String accNbr) {
		Debug("getOweInfo " + userId + "-" + accNbr);
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.GetOweInfo);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagAccNbr, accNbr);

		ReqParam req = new ReqParam(ReqType.GetOweInfo, reqSoap, ReqParam.GetOweInfo);
		sendReqAsync(req);
	}

	public void getOweInfoDetail(String userId, String servId, int pageSize, int pageNo) {
		Debug("getOweInfoDetail " + userId + "-" + servId);
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.GetOweInfoDetail);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagServId, servId);
		reqSoap.addProperty(TagPageSize, pageSize);
		reqSoap.addProperty(TagPageNo, pageNo);

		ReqParam req = new ReqParam(ReqType.GetOweInfoDetail, reqSoap, ReqParam.GetOweInfoDetail);
		sendReqAsync(req);
	}

	private static final String TagContent = "conten";
	private static final String TagPhone = "phone";

	public void sendUserFeedback(String userId, String content, String phone) {
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.SendUserFeedback);
		reqSoap.addProperty(TagUserId, userId);
		reqSoap.addProperty(TagContent, content);
		reqSoap.addProperty(TagPhone, phone);

		ReqParam req = new ReqParam(ReqType.SendUserFeedback, reqSoap, ReqParam.SendUserFeedback);
		sendReqAsync(req);
	}

	private static final String TagLogoName = "logonName";
	private static final String TagPasswd = "password";
	private static final String TagIMSI = "imsiCode";
	private static final String TagIMEI = "imeiCode";
	private static final String TagSysVer = "systemVersion";
	private static final String TagCliVer = "clientVersion";
	private static final String TagLontud = "longitude";
	private static final String TagLattud = "latitude";

	public void login(String passwd, String imsi, String imei, String sysVer, String ver, String lon, String lat) {
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.Login);
		reqSoap.addProperty(TagPasswd, passwd);
		reqSoap.addProperty(TagIMSI, imsi);
		reqSoap.addProperty(TagIMEI, imei);
		reqSoap.addProperty(TagSysVer, sysVer);
		reqSoap.addProperty(TagCliVer, ver);
		reqSoap.addProperty(TagLontud, lon);
		reqSoap.addProperty(TagLattud, lat);

		ReqParam req = new ReqParam(ReqType.Login, reqSoap, ReqParam.Login);
		sendReqAsync(req);
	}

	private static final String TagOldPasswd = "oldPassword";

	public void updatePattern(String imsi, String imei, String initPasswd, String passwd) {
		SoapObject reqSoap = new SoapObject(NAME_SPACE, ReqParam.UpdatePattern);
		reqSoap.addProperty(TagIMEI, imei);
		reqSoap.addProperty(TagIMSI, imsi);
		reqSoap.addProperty(TagOldPasswd, initPasswd);
		reqSoap.addProperty(TagPasswd, passwd);
		ReqParam req = new ReqParam(ReqType.UpdatePattern, reqSoap, ReqParam.UpdatePattern);
		sendReqAsync(req);
	}

	public RespResult doSoapAction(ReqParam.ReqType type, SoapObject request, String soapAction) {
		Debug("doSoap: " + type.toString() + "-" + soapAction);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.implicitTypes = true;
		envelope.dotNet = true;
		envelope.bodyOut = request;
		MyHttpTransportSE ht = new MyHttpTransportSE(URL);
		RespResult resp = new RespResult(type);
		try {
			ht.debug = true;
			ht.call(soapAction, envelope);
			Object Response = envelope.getResponse();
			String result = Response.toString();
			// Debug("r1. " + result);
			Debug("r1. " + ht.responseDump);
			writeFileData("ws", result, false);
			resp.setStatus(RespResult.STATUS_OK);
			// resp.setContent(result);
			resp.setContent(ht.responseDump);
			return resp;
		} catch (InterruptedIOException ex) {
			resp.setStatus(RespResult.STATUS_TIMEOUT);
			ex.printStackTrace();
			Debug("1. " + ex.getMessage());
		} catch (SocketException ex) {
			resp.setStatus(RespResult.STATUS_NETFAIL);
			ex.printStackTrace();
			Debug("2. " + ex.getMessage());
		} catch (Exception ex) {
			resp.setStatus(RespResult.STATUS_ERR_OTHERS);
			ex.printStackTrace();
			Debug("3. " + ex.getMessage());
		}
		return resp;
	}

	public void sendReqAsync(ReqParam req) {
		new AsyncSender(req, new Handler(), new CallbackRunnable()).start();
	}

	RespListener mRespListener = null;

	public void setRespListener(RespListener l) {
		mRespListener = l;
	}

	public class CallbackRunnable implements Runnable {

		RespResult response;

		@Override
		public void run() {
			// TODO Auto-generated method stub
			mRespListener.OnDataRecv(response);
		}

		public void setResponse(RespResult response) {
			this.response = response;
		}
	}

	static String TAG = "test";

	static void Debug(String info) {
		Utils.debug(TAG, "WSEngine " + info);
	}

}
